package com.beiding.jsonanalyzer.querylink;

import com.beiding.jsonanalyzer.analyze.func.FuncBase;
import com.beiding.jsonanalyzer.analyze.func.FuncFactory;
import com.beiding.jsonanalyzer.analyze.query.ComparatorResult;
import com.beiding.jsonanalyzer.exception.DataCheckException;
import com.beiding.jsonanalyzer.flow.BranchNode;
import com.beiding.jsonanalyzer.flow.ValueNode;
import com.beiding.jsonanalyzer.flow.flowevents.DataNodeEvent;

public class CheckQueryLinkNode<W extends ValueNode> extends ComputeNode<W> {

    private FuncFactory<FuncBase<ComparatorResult>> checker;

    public CheckQueryLinkNode(QueryLinkNode<W> pre, FuncFactory<FuncBase<ComparatorResult>> checker) {
        super(pre);
        this.checker = checker;
    }

    @Override
    protected void bindByComputeNode(BranchNode<W> preResult, BranchNode<W> newBranchNode) {

        FuncBase<ComparatorResult> baseQuery = checker.createInstance();

        ComputeNodeUtils.bindControlEvent(preResult, newBranchNode);
        preResult.onDataEvent(DataNodeEvent.eventType(), event -> {

            W data = event.getData();

            //执行所有的条件,如果有任何一个检查不通过,直接报错结束

            ComparatorResult comparatorResult = baseQuery.executeOne(data);
            if (comparatorResult != ComparatorResult.TRUE) {
                throw new DataCheckException("数据检查不通过!   数据=" + data.get() + "    检查器=" + baseQuery);
            }

            newBranchNode.signDataEvent(new DataNodeEvent<>(data));
        });

    }
}
